export const actionTypes = {
  getUserData: 'getUserData',
  setUserData: 'setUserData',
};

export const setUserData = (userData) => {
  return {
    type: actionTypes.setUserData,
    payload: userData,
  }
}

export const userDataKey = 'userData';

// export const setUserData = (userData) => async (dispatch, getState, api) => {
//   await new Promise((resolve) => {
//     setTimeout(() => {
//       console.log('setTimeout', api);
//       resolve('lalala');
//     }, 5000)
//   });
//   dispatch({
//     type: actionTypes.setUserData,
//     payload: userData,
//   });
//   return 'xixixi';
// }

export const getUserInfo = () => async (dispatch, getState, api) => {
  const res = await api.get('User/getUserInfo');

  if (res.data.data.id) {
    dispatch({
      type: actionTypes.setUserData,
      payload: { isLogin: true },
    });
  }
  return res;
}

export const login = (username, password) => async (dispatch, getState, api) => {
  const res = await api.post('User/login', {
    username,
    password,
  });

  const userData = {
    isLogin: true,
    ...res.data.data,
  };

  api.defaults.headers.common['token'] = userData.token;

  dispatch({
    type: actionTypes.setUserData,
    payload: userData,
  });

  try {
    window.localStorage.setItem(userDataKey, JSON.stringify(userData));
  } catch (e) {
    console.log('e');
  }

  return userData;
}

export const logout = (username, password) => async (dispatch, getState, api) => {
  await api.post('User/logout');

  api.defaults.headers.common['token'] = undefined;

  dispatch({
    type: actionTypes.setUserData,
    payload: undefined,
  });

  try {
    window.localStorage.removeItem(userDataKey);
  } catch (e) {
    console.log('e');
  }
}